<template>
  <div class="yy-month-reports">
    <!--列表-->
    <div class="yy-month-reports-list" v-show="type=='list'">
      <Card>
        <p slot="title">
          <Icon type="md-list" />
          月度结转报表
        </p>
        <Form ref="formInline" :model="formSearchMonth"  inline>
          <FormItem prop="user">
            <DatePicker type="date" placeholder="上次结存时间" style="width: 200px" v-model="formSearchMonth.lastDayDate" :options="startTimeOption" disabled></DatePicker>
          </FormItem>
          <FormItem prop="user">
            <DatePicker type="date" placeholder="本次结存时间" style="width: 200px" v-model="formSearchMonth.dayDate" :options="endTimeOption" @on-change="onEndTimeChange" ></DatePicker>
          </FormItem>
          <FormItem prop="user">
            <Select class="select" v-model="formSearchMonth.storageNum" placeholder="请选择仓库" clearable>
              <Option v-for="(dataSt,index) in this.currentList.cangkuA1" :value="dataSt.storageNum" :key="index">{{dataSt.storageName}}</Option>
            </Select>
          </FormItem>
          <FormItem>
            <div style="width: 56px;">
              <Button type="primary" :loading="loading"  @click="handleSearch()" style="width: 100%">
                <span v-if="!loading">查询</span>
                <span v-else></span>
              </Button>
            </div>
          </FormItem>
          <FormItem>
            <Button type="primary" :loading="monthList" @click="handleSearchTurn()">
            <span v-if="!monthList">结存当月</span>
            <span v-else></span>
            </Button>
          </FormItem>
        </Form>

        <Divider style="font-size: 20px;">月度汇总表</Divider>

        <Table highlight-row stripe :columns="columns" :data="data"></Table>
        <Table :columns="columnsExcel" :data="dataExcel" border ref="tables" style="display: none;"></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
            <Page :total="page.total" :page-size="page.pageSize" :current="formSearch.pageNum" @on-change="changePage" show-total></Page>
          </div>
        </div>
      </Card>
    </div>
    <!--详情-->
    <div class="yy-month-reports-details" v-show="type=='details'">
       <Card>
        <p slot="title">
          <Icon type="md-paper"/>
          月度转结详情
          <p slot="extra">
            <Button type="primary" class="buttonExcel" @click="handlePrint()">打印</Button>
            <Button :loading="loadingExcel" type="primary" class="buttonExcel" @click="getExcelList()">
            <span v-if="!loadingExcel">导出</span>
            <span v-else></span>
            </Button>
            <Button type="primary" @click="goBack()">返回</Button>
          </p>
        </p>
        <Divider style="font-size: 20px;">月度汇总表 {{startTime}}</Divider>
        <div class="count">合计： 入库：{{pageSubtotal.inAmountTotal}}    出库：{{pageSubtotal.outAmountTotal}}</div>
        <div class="sub-count">
          合计：初期库存：数量{{pageSubtotal.startNumTotal}} 金额{{pageSubtotal.startAmountTotal}} 
          | 本期收入：数量{{pageSubtotal.inNumTotal}} 金额{{pageSubtotal.inAmountTotal}} 
          | 本期发出：数量{{pageSubtotal.outNumTotal}} 金额{{pageSubtotal.outAmountTotal}} 
          | 期末结存：数量{{pageSubtotal.numTotal}} 金额{{pageSubtotal.amountTotal}}
        </div>
        <Table highlight-row stripe :columns="columnsA" :data="dataB" border></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
            <Page :total="pageA.total" :page-size="pageA.pageSize" :current="formSearch.pageNum" @on-change="changePageMonth" show-total></Page>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import API from "./api";
import ValidatorRule from "@/filters/validator-rule";
import { formatNetTime } from "@/libs/tools";
import i18n from "./locale";
import mixin from "@/mixin/date-mixin";
import wareHouseMixin from "../common/warehouse-mixin";
import mixinTag from "@/mixin/tag-mixin";

export default {
  name: "yy-month-reports",
  mixins: [mixin, wareHouseMixin, mixinTag],
  data() {
    return {
      i18n: i18n,
      loading: false,
      loadingExcel: false,
      monthList: false,
      currentData: null,
      detailsModal: false,
      startTime: "",
      storageNumExcel: "",
      type: "list",
      endTimeOption: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      page: {
        total: 0,
        pageSize: 20
      },
      pageA: {
        total: 0,
        pageSize: 20
      },
      pageSubtotal: {
        startNumTotal: 0,
        startAmountTotal: 0,
        inNumTotal: 0,
        inAmountTotal: 0,
        outNumTotal: 0,
        outAmountTotal: 0,
        numTotal: 0,
        amountTotal: 0
      },
      formSearch: {
        //历史结存总汇表
        storageNum: "",
        storageNums: ["1", "2", "3"],
        userID: "",
        userName: "",
        pageNum: ""
      },
      formSearchMonth: {
        //结存当月数据
        storageNum: "",
        //storageNums: ["1","2","3"],
        lastDayDate: "",
        dayDate: new Date(),
        userID: "",
        userName: ""
      },
      editFormInLine: {},
      editFormRuleInline: {},
      columns: [
        {
          title: "序号",
          type: "index"
        },
        {
          title: "仓库",
          key: "storageName"
        },
        {
          title: "时间",
          key: "dayDate"
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          render: (h, params) => {
            let viewAction = h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small"
                },
                style: {
                  marginRight: "5px"
                },
                on: {
                  click: () => {
                    this.details(params.index);
                  }
                }
              },
              "查看"
            );

            let deleteAction = h(
              "Button",
              {
                props: {
                  type: "error",
                  size: "small"
                },
                style: {
                  marginRight: "5px"
                },
                on: {
                  click: () => {
                    this.delete(params.index, params.row.id);
                  }
                }
              },
              "删除"
            );

            //根据角色判断操作按钮的显示
            let arr = "";
            if (params.index == 0) {
              arr = [viewAction, deleteAction];
            } else {
              arr = [viewAction];
            }
            return h("div", arr);
          }
        }
      ],
      data: [],
      columnsA: [
        {
          title: "物品编号",
          align: "center",
          key: "itemNum",
          width: 100
        },
        {
          title: "物品名称",
          align: "center",
          key: "itemName"
        },
        {
          title: "规格",
          align: "center",
          key: "size"
        },
        {
          title: "计量单位",
          align: "center",
          key: "unitName"
        },
        {
          title: "初期库存",
          align: "center",
          children: [
            {
              title: "数量",
              key: "startNum",
              align: "center"
            },
            {
              title: "金额(元)",
              key: "startAmount",
              align: "center"
            }
          ]
        },
        {
          title: "本期收入",
          align: "center",
          children: [
            {
              title: "数量",
              key: "inNum",
              align: "center"
            },
            {
              title: "金额(元)",
              key: "inAmount",
              align: "center"
            }
          ]
        },
        {
          title: "本期发出",
          align: "center",
          children: [
            {
              title: "数量",
              key: "outNum",
              align: "center"
            },
            {
              title: "金额(元)",
              key: "outAmount",
              align: "center"
            }
          ]
        },
        {
          title: "期末结存",
          align: "center",
          children: [
            {
              title: "数量",
              key: "num",
              align: "center"
            },
            {
              title: "金额(元)",
              key: "amount",
              align: "center"
            }
          ]
        }
      ],
      dataB: [],
      dataTatol: [], //算页面小计
      columnsExcel: [
        {
          title: "物品编号",
          align: "center",
          key: "itemNum",
          width: 100
        },
        {
          title: "物品名称",
          align: "center",
          key: "itemName"
        },
        {
          title: "规格",
          align: "center",
          key: "size"
        },
        {
          title: "计量单位",
          align: "center",
          key: "unitName"
        },
        {
          title: "数量(初期库存)",
          key: "startNum",
          align: "center"
        },
        {
          title: "金额(元)(初期库存)",
          key: "startAmount",
          align: "center"
        },
        {
          title: "数量(本期收入)",
          key: "inNum",
          align: "center"
        },
        {
          title: "金额(元)(本期收入)",
          key: "inAmount",
          align: "center"
        },
        {
          title: "数量(本期发出)",
          key: "outNum",
          align: "center"
        },
        {
          title: "金额(元)(本期发出)",
          key: "outAmount",
          align: "center"
        },
        {
          title: "数量(期末结存)",
          key: "num",
          align: "center"
        },
        {
          title: "金额(元)(期末结存)",
          key: "amount",
          align: "center"
        }
      ],
      dataExcel: []
    };
  },

  mounted() {
    this.userInfo = this.$store.state.user.userInfo;
    this.handleSearch();
  },

  activated() {},

  computed: {},

  methods: {
    resetInit() {
      this.handleSearch();
      this.type = "list";
    },

    handleSearch() {
      let obj = this.formSearch;
      obj.userID = this.userInfo.userId;
      obj.storageNum = this.formSearchMonth.storageNum;
      obj.pageNum = 1;
      obj.pageSize = this.page.pageSize;
      this.formSearch = obj;
      this.getList(obj);
    },

    getList(obj) {
      this.loading = true;
      API.getList(obj)
        .then(res => {
          if (res.code == 200) {
            this.loading = false;
            let data = res.data;
            if (data != null) {
              this.page.total = data.total;
              this.data = data.list;
              this.formSearchMonth.lastDayDate = new Date(data.list[0].dayDate);
            } else {
              this.$Message.success({ content: "暂无数据！" });
              this.data = [];
              this.page.total = 0;
            }
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
          console.log("getList", err);
        });
    },

    //结存当月
    handleSearchTurn() {
      let obj = _.clone(this.formSearchMonth);
      if (obj.storageNum != "") {
        obj.lastDayDate = "";
        obj.dayDate = this.UTC(obj.dayDate, "time");
        obj.userID = this.userInfo.userId;
        this.monthList = true;
        API.checkMonth(obj)
          .then(res => {
            if (res.code == 200) {
              this.monthList = false;
              this.resetList();
              this.$Message.success("结算成功！");
              this.goBack();
            }
          })
          .catch(err => {
            this.$Message.warning("请求异常！");
            console.log("handleSearchTurn", err);
          });
      } else {
        this.$Message.error("请选择结存的仓库！");
      }
    },

    changePage(pageNum) {
      let obj = this.formSearch,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearch = obj;
      this.getList(obj);
    },

    goBack() {
      this.type = "list";
    },

    details(index) {
      this.type = "details";
      let obj = _.clone(this.formSearchMonth);
      obj.pageNum = 1;
      obj.pageSize = this.pageA.pageSize;
      obj.lastDayDate = "";
      obj.storageNum = this.data[index].storageNum;
      obj.dayDate = this.data[index].dayDate;
      this.storageNumExcel = obj.storageNum;
      this.startTime = _.clone(obj.dayDate);
      this.getDetails(obj);
    },

    getDetails(obj) {
      API.getDetails(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            if (data != null) {
              this.pageA.total = data.total;
              this.dataTatol = data;
              this.dataB = data.list;
              //this.thisPageSubtotal();
              this.pageSubtotal = data.dataInfo;
              this.thisinOutTotal();
            } else {
              this.$Message.success({ content: "本条结存，没有数据！" });
              this.dataB = [];
            }
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
          console.log("getDetails", err);
        });
    },

    thisinOutTotal() {
      this.pageSubtotal.startNumTotal = parseInt(
        this.pageSubtotal.startNumTotal
      );
      this.pageSubtotal.inNumTotal = parseInt(this.pageSubtotal.inNumTotal);
      this.pageSubtotal.outNumTotal = parseInt(this.pageSubtotal.outNumTotal);
      this.pageSubtotal.numTotal = parseInt(this.pageSubtotal.numTotal);

      this.pageSubtotal.startAmountTotal = this.pageSubtotal.startAmountTotal.toFixed(
        2
      );
      this.pageSubtotal.inAmountTotal = this.pageSubtotal.inAmountTotal.toFixed(
        2
      );
      this.pageSubtotal.outAmountTotal = this.pageSubtotal.outAmountTotal.toFixed(
        2
      );
      this.pageSubtotal.amountTotal = this.pageSubtotal.amountTotal.toFixed(2);
    },

    changePageMonth(pageNum) {
      let obj = this.formSearchMonth,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearchMonth = obj;
      obj.dayDate = this.startTime;
      obj.lastDayDate = "";
      obj.storageNum = this.storageNumExcel;
      obj.pageSize = this.pageA.pageSize;
      this.getDetails(obj);
    },

    delete(index, id) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除这条记录",
        onOk: function() {
          let obj = {
            storageNum: tthis.data[index].storageNum,
            dayDate: tthis.data[index].dayDate,
            userID: tthis.userInfo.userId,
            userName: tthis.userInfo.userName
          };
          API.delete(obj)
            .then(res => {
              if (res.code == 200) {
                this.$Message.success({ content: "该记录已经删除成功！" });
                tthis.data.splice(index, 1);
                tthis.resetList();
              }
            })
            .catch(err => {
              this.$Message.error("请求异常！");
              console.log("delete", err);
            });
        }
      });
    },

    resetList() {
      //求余为1，页码为最大页码，请求页需减1
      let maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      let remainderNum = this.page.total % this.page.pageSize;
      if (
        this.formSearch.pageNum == maxPageNum &&
        remainderNum == 1 &&
        this.formSearch.pageNum !== 1
      ) {
        this.formSearch.pageNum = this.formSearch.pageNum - 1;
      }
      let obj = this.formSearch;
      this.getList(obj);
    },

    thisPageSubtotal() {
      let obj = {
        startNumTotal: 0,
        startAmountTotal: 0,
        inNumTotal: 0,
        inAmountTotal: 0,
        outNumTotal: 0,
        outAmountTotal: 0,
        numTotal: 0,
        amountTotal: 0
      };
      for (let i in this.dataB) {
        obj.startNumTotal += this.dataB[i].startNum;
        obj.startAmountTotal += this.dataB[i].startAmount * 100;
        obj.inNumTotal += this.dataB[i].inNum;
        obj.inAmountTotal += this.dataB[i].inAmount * 100;
        obj.outNumTotal += this.dataB[i].outNum;
        obj.outAmountTotal += this.dataB[i].outAmount * 100;
        obj.numTotal += this.dataB[i].num;
        obj.amountTotal += this.dataB[i].amount * 100;
      }
      obj.startAmountTotal = obj.startAmountTotal / 100;
      obj.inAmountTotal = obj.inAmountTotal / 100;
      obj.outAmountTotal = obj.outAmountTotal / 100;
      obj.amountTotal = obj.amountTotal / 100;
      this.pageSubtotal = obj;
    },

    handlePrint() {
      window.print();
    },

    getExcelList() {
      let obj = _.clone(this.formSearchMonth);
      obj.pageNum = 1;
      obj.pageSize = this.pageA.total;
      console.log("导出数据的条数", obj.pageSize);
      obj.dayDate = this.startTime;
      obj.storageNum = this.storageNumExcel;
      obj.lastDayDate = "";
      if (this.loadingExcel == false) {
        this.getDetailsA(obj);
      }
    },

    getDetailsA(obj) {
      this.loadingExcel = true;
      API.getDetails(obj)
        .then(res => {
          if (res.code == 200) {
            this.loadingExcel = false;
            let data = res.data;
            if (data != null) {
              this.dataExcel = data.list;
              this.handleExcel();
            } else {
              this.$Message.success({ content: "暂无数据！" });
              this.dataExcel = [];
            }
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
          console.log("getListA", err);
        });
    },

    handleExcel() {
      this.$refs.tables.exportCsv({
        filename: "月度结转数据",
        columns: this.columnsExcel,
        data: this.dataExcel
      });
      this.$Message.success({ content: "导出Excel成功！" });
      this.dataExecl = [];
    }
  }
};
</script>
<style lang="less" >
@import "./yy-month-reports.less";
</style>
